//
//  CustomImageView.m
//  TestSD
//
//  Created by shaop on 2016/11/21.
//  Copyright © 2016年 shaop. All rights reserved.
//

#import "CustomImageView.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface CustomImageView(){
    int index;
    int findex;
    int endindex;
    int endx;
}
@property(nonatomic , strong) NSArray *imageArr;
@end

@implementation CustomImageView

-(id)init{
    self = [super init];
    if (self) {
        
//        self.imageArr = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8", nil];
        index = 0;
        findex = 0;
        endindex = 0;
        UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
        [self addGestureRecognizer:recognizer];
        
        [self setUserInteractionEnabled:YES];
        [self setMultipleTouchEnabled:YES];
    }
    return self;
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        
//        self.imageArr = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8", nil];
        index = 0;
        findex = 0;
        endindex = 0;
        UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
        [self addGestureRecognizer:recognizer];
        
        [self setUserInteractionEnabled:YES];
        [self setMultipleTouchEnabled:YES];
    }
    return self;
}

-(void)setImageArr:(NSArray *)imageArr{
    _imageArr = imageArr;
    [self sd_setImageWithURL:_imageArr[0]];
}

-(void)handleSwipe:(UIPanGestureRecognizer *)gesture{
    CGPoint translation = [gesture translationInView:self];
    
    
    if (translation.x>0) {
        index = endindex + translation.x/30 ;
        index = index % self.imageArr.count;
        [self sd_setImageWithURL:_imageArr[index]];
    }
    
    if (translation.x<-1) {
        
        int trans = ((int)translation.x/30 + endx)% (int)self.imageArr.count;
        findex = (int)self.imageArr.count - 1 + trans;

        if (findex<self.imageArr.count) {
            [self sd_setImageWithURL:_imageArr[findex]];
        }

    }
    
    if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled) {
        if (translation.x > 0) {
            endindex = index;
            endx = index - ((int)self.imageArr.count - 1);
        }else{
            endindex = findex;
            endx = findex - ((int)self.imageArr.count - 1);
        }

    }
    
}

@end
